<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="460px" @close="handleReset">
    <div v-loading="loading" :element-loading-text="loadText" style="display: flex;align-items: center;justify-content: center; flex-direction: column;">
      <slot />
      <p style="text-align: left;width: 100%;margin: 0 auto;padding:0 30px;padding-bottom: 8px;" class="flex">
        <a :href="baseUrl+'comsumer/downloadCsv?file=词库关键词上传模板.csv'" download="词库关键词上传模板">
          <em class="min-text" style="padding-top: 14px;">
            下载模板</em>
        </a>
        <span class="min-text">{{ wordsList.length }}/5000</span>
      </p>
      <el-upload
        ref="uploaddemo"
        class="upload-demo"
        drag
        :auto-upload="false"
        accept=".csv"
        :on-change="handlechange"
        :on-remove="removeDate"
        :file-list="fileList"
        show-file-list
        :disabled="wordsList.length>=5000"
        :limit="1"
        :multiple="false"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          <p style="padding-bottom: 6px;">点击或将文件拖拽到这里上传</p>
          <p class="el-upload__tip">仅支持扩展名:.csv
          </p>
        </div>
      </el-upload>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" class="cancel-btn defult" @click="handleReset">取 消</el-button>
      <el-button type="success" size="small" class="defult" @click="handleSub">上 传</el-button>
    </span>
  </el-dialog>
</template>

<script>
import Papa from 'papaparse'
import jschardet from 'jschardet'
import iconv from 'iconv-lite'
import encoding from 'encoding'
export default {
  props: {
    beforeUpload: {
      type: Function,
      default: () => {
        return true
      }
    },
    title: {
      type: String,
      default: '上传关键词'
    },
    isNegative: {
      type: Boolean, // 是否是否定关键词上传
      default: false
    },

    visible: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      loading: false,
      loadText: true,
      dialogVisible: false,
      fileList: [], // 批量上传关键词
      wordsList: []
    }
  },

  computed: {

  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
    }

  },

  methods: {
    handleReset() {
      if (this.loading) return false
      this.fileList = []
      this.wordsList = []
      this.dialogVisible = false
      this.$emit('update:visible', false)
    },

    handleSub() {
      const falg = this.beforeUpload()
      if (!falg) return false

      if (!this.fileList.length) {
        this.$message.closeAll()
        this.$message({
          type: 'warning',
          message: '请先选择文件'
        })
      } else {
        this.loading = true
        this.loadText = '正在为您处理文件数据，请稍后'
        const arr = []
        this.loadText = '数据处理完毕，上传中。请稍候'
        setTimeout(() => {
          this.fileList = []
          this.wordsList = []
          this.loading = false
          this.dialogVisible = false
        }, 1000)

        let data = []
        if (this.isNegative) {
          data = this.wordsList.map(item => {
            const obj = {}
            obj.matchType = item.Match_Type
            obj.text = item.Negative_Keyword.replace(/\s+/ig, ' ')
            return obj
          })
        } else {
          data = this.wordsList.map(item => {
            const obj = {}
            obj.matchType = item.MatchType
            obj.text = item.Keyword.replace(/\s+/ig, ' ')

            return obj
          })
        }
        this.$emit('handleAddWords', data)
      }
    },
    /* 移除文件*/
    removeDate(file, fileList) {
      this.fileList = []
    },

    // 文件發生了改變
    handlechange(file, fileList) {
      const that = this
      this.parseData(file, function(res) {
        if (res.length && res.length <= 5000) {
          if (that.isNegative) {
            // 如果是否定关键词
            if (res[0].Match_Type && res[0].Negative_Keyword) {
              that.fileList = fileList
            } else {
              that.$message.closeAll()
              that.$message.error('文件不符合否定关键词模板格式或有必填项未填写,请检查')
              that.fileList = []
              return false
            }

            const arr = []
            const reportArr = [] // 重名的数组
            res.forEach(item => {
              const index = arr.findIndex(v => {
                return item.Negative_Keyword === v.Negative_Keyword && item.Match_Type === v.Match_Type
              })
              if (index === -1) {
                arr.push(item)
              } else {
                reportArr.push(item)
              }
            })

            if (reportArr.length) {
              const str =
                  `此文件内“${reportArr[0].Negative_Keyword}”${reportArr.length > 1 ? `等${reportArr.length}项` : ''}屏蔽词重复,已自动为您过滤`
              that.$message({

                message: str,
                type: 'warning'
              })
            }
            that.wordsList = arr
            that.fileList = fileList
          } else {
            // 如果是投放关键词
            if (res[0].Keyword && res[0].MatchType) {
              that.fileList = fileList
            } else {
              that.$message.closeAll()
              that.$message.error('文件不符合关键词模板格式')
              that.fileList = []
              return false
            }
            const arr = []
            const reportArr = [] // 重名的数组
            res.forEach(item => {
              const index = arr.findIndex(v => {
                return item.MatchType === v.MatchType && item.Keyword === v.Keyword
              })
              if (index !== -1) {
                reportArr.push(item)
              } else {
                arr.push(item)
              }
            })
            if (reportArr.length) {
              const str =
                  `此文件内“${reportArr[0].Keyword}”${reportArr.length > 1 ? `等${reportArr.length}项` : ''}关键词重复,已自动为您过滤`
              that.$message({
                showClose: true,
                message: str,
                type: 'warning'
              })
            }

            that.fileList = fileList
            that.wordsList = arr
          }
        } else {
          that.$message.closeAll()
          that.$message.error(res.length ? '此文件关键词数量超过5000' : '此文件没有数据,请重新上传')
          that.fileList = []
          that.wordsList = []
        }
      })
    },

    // 处理解析文件
    parseData(file, callback) {
      const wordsList = []
      let selectedFile = null
      selectedFile = file.raw
      if (selectedFile === undefined) {
        return undefined
      }
      let allResults = []
      var reader = new FileReader()
      reader.readAsBinaryString(selectedFile)
      reader.onload = evt => {
        let buf = evt.target.result
        const encodeType = jschardet.detect(buf).encoding
        if (encodeType !== 'UTF-8') {
          buf = encoding.convert(buf, 'utf8', encodeType)
        }
        iconv.skipDecodeWarning = true
        const text = iconv.decode(buf, 'utf8')
        Papa.parse(text, {
          encoding: 'UTF-8',
          complete: results => {
            for (let y = 0; y < results.data.length; y++) {
              // es6合并数组的语法
              allResults = [...allResults, results.data[y]]
            }
            // 打印拿到的最终数据
            if (allResults[allResults.length - 1] === '') {
              // 去除最后的空行
              allResults.pop()
            }
            allResults.pop()
            allResults.forEach((item, index) => {
              var obj = {}
              if (index !== 0) {
                item.forEach((subItem, subIndex) => {
                  const key = allResults[0][subIndex]
                  obj[key] = subItem
                })

                wordsList.push(obj)
              }
            })

            callback && callback(wordsList)
          }
        })
      }
    }

    /* 批量上传关键词结束*/

  }
}
</script>

<style>
</style>
